package com.outsourcing.bottle.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

import com.outsourcing.bottle.BasicActivity;
/**
 * 
 * @author 06peng
 *
 */
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { 
	
	public Thread.UncaughtExceptionHandler a; 
    public BasicActivity  basicActivity;

	public MyUncaughtExceptionHandler(BasicActivity basicActivity) {
		this.a = Thread.getDefaultUncaughtExceptionHandler();
	}

	@Override 
	public void uncaughtException(Thread thread, Throwable ex) { 
		killProcess();
    } 

	private void killProcess() {
		String packageName = "com.outsourcing.bottle";
		String processId = "";
		try {
			Runtime r = Runtime.getRuntime();
			Process p = r.exec("ps");
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String inline;
			while ((inline = br.readLine()) != null) {
				if (inline.contains(packageName)) {
					break;
				}
			}
			br.close();
			StringTokenizer processInfoTokenizer = new StringTokenizer(inline);
			int count = 0;
			while (processInfoTokenizer.hasMoreTokens()) {
				count++;
				processId = processInfoTokenizer.nextToken();
				if (count == 2) {
					break;
				}
			}
			r.exec("kill -15 " + processId);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}


